package cn.net.isir.service2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.WxErrCode;
import cn.net.isir.common.config.WxConfig;
import cn.net.isir.common.AES;
import cn.net.isir.utils.HttpUtil2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxubo
 * @filename WxInterfaceService.java
 * @package cn.net.isir.service2
 * @email lxb@isir.net.cn
 * @date 2018/08/28
 * @comment
 * @since 1.7
 */
@Service("minipWxInterfaceService")
@Transactional
public class WxInterfaceService {
    // 声明log4j日志
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(WxInterfaceService.class);

    /**
     * 获取微信openid和sessionid
     *
     * @param jsCode 登录时获取的 code
     * @return 返回map
     */
    public Map<String, Object> getOpenid(String jsCode) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", WxConfig.getSub_appid());
        paramMap.put("secret", WxConfig.getSub_appSecret());
        paramMap.put("js_code", jsCode);
        paramMap.put("grant_type", "authorization_code");
        String getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String resultStr = HttpUtil2.sendGetByUrlConnection(getOpenIdUrl, paramMap, "utf-8");
        JSONObject jsonObject = JSON.parseObject(resultStr);
        // 如果获取不到openid，表示请求出错了，返回错误信息
        if (jsonObject.get("openid") == null) {
            return jsonObject;
        }
        // 微信公众平台中，0表示请求成功
        jsonObject.put("errcode", 0);
        return jsonObject;
    }

    /**
     * 解密数据
     *
     * @param encryptedDatam 加密数据
     * @param sessionKey     sessionKey
     * @param iv             初始向量
     * @return 解密后的对象
     */
    public Map<String, Object> getUnionid(String encryptedDatam, String sessionKey, String iv) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes;
        try {
            bytes = AES.decrypt(decoder.decode(encryptedDatam), decoder.decode(sessionKey), AES.generateIV(decoder.decode(iv)));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        try {
            return JSON.parseObject(new String(bytes, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("数据解密失败");
            return null;
        }
    }

    public static void main(String[] args) {
        Map a = new WxInterfaceService().getOpenid(null);
        logger.info(a.size());
        logger.info(JSON.toJSONString(a));
        logger.info(WxErrCode.wxPayErr(String.valueOf(a.get("errcode"))));
    }
}
